<!--
 * @description  : 中小学坐标采集-新增编辑出入口
 * @descriptionDetail : 中小学坐标采集-新增编辑出入口
 * @author       : bln
 * @create       : 2024-09-02 00:00:00
-->

<template>
  <view class="page">
    <!-- #ifdef H5-ONLY -->
    <theme-navbar :is-white="false" :title="navTitle" :custom-back="goBack" style="z-index: 99999"> </theme-navbar>
    <!-- #endif -->
    <view class="m-content">
      <view class="tip">
        <view :style="{ display: 'inline-block', marginRight: '10rpx' }">拖动</view>
        <u-image width="16px" src="/static/certificate/position_picker.png" mode="widthFix"></u-image>
        <view :style="{ display: 'inline-block', marginLeft: '36rpx' }">进行描点选址</view>
      </view>
      <view :style="{ width: getContainerWidth(), height: getContainerHeight() }" id="container"></view>
      <view class="m-market">
        <u-form :model="pointForm" :rules="rules" :errorType="['border-bottom', 'message']" style="padding: 15px;" ref="pointForm">
			<u-form-item label="坐标名称" prop="pointName" :label-width="180" required>
            <u-input v-model="pointForm.pointName" placeholder="请输入坐标名称" />
          </u-form-item>
          <u-form-item label="位置类型" prop="positionType" :label-width="180" right-icon="arrow-right" required>
            <u-input v-model="pointForm.positionTypeName" placeholder="请选择位置类型" @click="showPositionType = true" />
            <u-select :list="positionTypeList" v-model="showPositionType" @confirm="positionTypeConfirm" />
          </u-form-item>
          <u-form-item label="经纬度" prop="coordinates" :label-width="180" required>
            <u-input v-model="pointForm.coordinates" placeholder="请选择点坐标" :clearable="false" :disabled="true" />
            <img src="static/cur-loc-gree.png" width="25" height="25" @click="setLocation" />
          </u-form-item>
		    </u-form>
        <u-row class="row">
          <u-col :span="12" class="row-button">
            <u-button type="primary" @click="submit">确定</u-button>
          </u-col>
        </u-row>
      </view>
    </view>
  </view>
</template>

<script>
import { AMapMixin } from '@/common/AMapMixin.js'
import { SET_MAP_LAT_LON } from '@/config/setting.config.js'

export default {
  mixins: [AMapMixin],
  data() {
    return {
      isBeyond: false,
      showPositionType: false,
      positionPicker: undefined,
      curCords: null,
      handleType: 'add',
      curEntityName: '',
      pointForm: {
        pointName: '',
        coordinates: '',
        positionTypeName: '',
      },
      positionTypeList: [
        { value: '1', label: '中心点' },
        { value: '3', label: '出入口' }
      ],
      rules: {
        pointName: [
          {
            required: true,
            message: '请输入坐标名称',
            trigger: ['change', 'blur']
          }
        ],
        positionType: [
          {
            required: true,
            message: '请选择位置类型',
            trigger: ['change', 'blur']
          }
        ],
        coordinates: [
          {
            required: true,
            message: '请选择点坐标',
            trigger: ['change', 'blur']
          }
        ]
      }
    }
  },
  onReady() {
    this.$refs.pointForm && this.$refs.pointForm.setRules(this.rules)
  },
  onLoad() {
    const { type, pointInfo } = this.getRouteParam()
    this.handleType = type
    this.pointForm = { ...pointInfo }
  },
  methods: {
    // 位置类型选择
    positionTypeConfirm(e) {
      this.pointForm.positionType  = e[0].value
      this.pointForm.positionTypeName = e[0].label
    },
    justInitMap() {
      this.$modal.alert('请在设备的设置中开启APP的定位权限后重新获取当前位置');
      this.amap = new AMap.Map('container', {
        showControlButton: true,
        zoom: 18
      })
      let self = this
      this.$modal.hideLoading();
      AMapUI.loadUI(['misc/PositionPicker'], function(PositionPicker) {
        AMap.PositionPicker = PositionPicker
        self.loadMarkList()
      })
    },
    setLocation() {
      let self = this
      // #ifdef H5-DINGDING || H5-WECHAT || H5-EMP
      this.$deviceApi.geolocation().then(res => {
        self.curCords = [res.longitude, res.latitude]
        self.setMapInstance()
      },err => {
        self.justInitMap()
      })
      // #endif
      // #ifdef H5-ONLY
      self.curCords = SET_MAP_LAT_LON
      self.setMapInstance()
      // #endif
    },
    initAmap() {
      if(this.pointForm.coordinates) {
        const location = this.pointForm.coordinates.split(',')
        this.curCords = new AMap.LngLat(location[0], location[1])
        this.setMapInstance()
      } else {
        this.setLocation()
      }
    },
    getContainerHeight() {
      let p = this.$u.sys().windowHeight - 44 - this.$u.sys().statusBarHeight - 33 + 'px'
      // #ifdef H5-DINGDING || H5-WECHAT
      p = this.$u.sys().windowHeight - this.$u.sys().statusBarHeight + 'px'
      // #endif
      return p
    },
    getContainerWidth() {
      return this.$u.sys().windowWidth + 'px'
    },
    setMapInstance() {
      if (!this.hasInited) return
      this.amap = new AMap.Map('container', {
        center: this.curCords,
        showControlButton: true,
        zoom: 18
      })
      const _this = this
      this.loadPlugin('AMap.ControlBar', function() {
        const controlBar = new AMap.ControlBar({
          position: {
            top: '10px',
            right: '10px'
          }
        })
        _this.amap.addControl(controlBar)
      })
      this.drawDefaultInstance()
    },
    // 绘制地图默认实例 当前位置 & 选址图标
    drawDefaultInstance() {
      const curLocation = new AMap.Marker({
        title: '当前位置',
        icon: new AMap.Icon({
          size: new AMap.Size(20, 30),
          imageSize: new AMap.Size(20, 30),
          image: 'static/market/new-location.png' // 大图地址
        }),
        position: this.curCords
      })
      curLocation.setMap(this.amap)
      const _this = this
      AMapUI.loadUI(['misc/PositionPicker'], function(PositionPicker) {
        AMap.PositionPicker = PositionPicker
        _this.loadMarkList()
      })
    },
    loadMarkList() {
      let self = this
      self.positionPicker = new AMap.PositionPicker({
        mode: 'dragMarker',
        map: self.amap,
        iconStyle: {
          url: require('@/static/certificate/position_picker.png'),
          ancher: [30, 60],
          size: [30, 40]
        }
      })
      self.amap.on('click', function(positionResult) {
        self.positionPicker.start(new AMap.LngLat(positionResult.lnglat.getLng(), positionResult.lnglat.getLat()))
      })
      // 修改选址
      self.positionPicker.on('success', function(positionResult) {
        // 限制200m提示
        self.isBeyond = false;
        const distance = Math.round(self.curCords.distance(positionResult.position));
        if (distance > 200) {
          self.isBeyond = true;
          uni.showToast({
            title: "该中小学、幼儿园距离当前位置超过200米，请重新选址。",
            icon: "none",
            duration: 2000
          })
		  return
        }
        self.pointForm.coordinates = `${positionResult.position.getLng()},${positionResult.position.getLat()}`
        self.$forceUpdate()
      })
      self.positionPicker.on('fail', function(positionResult) {
        console.log('获取点坐标失败')
      })
      if (self.curCords) {
        self.positionPicker.start(self.curCords)
        self.pointForm.coordinates = Array.isArray(self.curCords) ? self.curCords.join() : `${self.curCords.getLng()},${self.curCords.getLat()}`
        self.$forceUpdate()
      }
      self.amap.panBy(0, 1)
    },
    // 提交新增的实体
    submit() {
      this.$refs.pointForm.validate(valid => {
        if (valid) {
          // 限制200m提示
          if (this.isBeyond) {
            uni.showToast({
              title: '该中小学、幼儿园距离当前位置超过200米，请重新选址。',
              icon: 'none'
            })
            return
          }
          this.backPrev({
            paramKey: 'pointInfo',
            param: {
              type: this.handleType,
              info: { ...this.pointForm, editable: true }
            }
          })
        }
      })
    }
  }
}
</script>

<style scoped lang="scss">
uni-page-body {
  min-height: 100%;
  width: 100%;
  background-color: #f1f0f6;
}

.page {
  padding: 0;
}

#container {
  /* #ifdef H5 */
  width: 100%;
  height: calc(100% - 30rpx);
  /* #endif */
  /* #ifdef APP-PLUS */
  height: calc(100vh - 44 - var(--status-bar-height));
  margin-top: calc(44 + var(--status-bar-height));
  /* #endif */
}

.tip {
  background-color: #f6f6f6;
  height: 60rpx;
  line-height: 60rpx;
  text-align: center;
  position: relative;
}

.m-market {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  z-index: 999;
  background-color: #ffffff;
  padding: 0 30rpx;
}

.row {
  padding-top: 20rpx;
  position: relative;
  color: #666666;
  .row-value {
    color: #333333;
    font-weight: bold;
  }
  .row-button {
    padding: 0 !important;
    margin-bottom: 20rpx;
  }
  .arrow {
    position: absolute;
    right: 0;
    color: #333333;
  }
  /deep/.u-col {
    padding-bottom: 10rpx !important;
  }
}
/deep/.u-image {
  display: inline-block;
  position: absolute;
  top: 8rpx;
}
.u-size-default {
  font-size: 28rpx;
}
</style>
